using System;
using Rapier.Kodachi.Shared;
using System.Net;
using System.Data;
using System.Drawing;
using System.Threading;
using System.Diagnostics;
using System.Web;

namespace Rapier.Kodachi.Weather.Actions
{
    public class Forecast : Action
    {
        #region Constructor
        public Forecast(Plugin plugin)
            : base(plugin, "Rapier.Kodachi.Weather.Forecast", "Extended Forecast", "Get the extended forecast for your location.")
        {
            GetImage = delegate() { return new System.Drawing.Bitmap((Bitmap)Rapier.Kodachi.Weather.Properties.Resources.ResourceManager.GetObject("_37")); };
        }
        #endregion

        #region Action Members
        public override void Execute(Item[] directItems, Item[] indirectItems)
        {
            string address = @"http://xoap.weather.com/weather/local/" + WeatherPlugin.WeatherSettings.DefaultLocationID + "?cc=*&dayf=10&prod=xoap&par=1007433109&key=f15e225f602adebb";
            if (WeatherPlugin.WeatherSettings.UseCelsius)
                address += "&unit=m";

            DataSet weatherDS = WeatherShared.GetWeatherData(address);
            WeatherShared.PrintDataSet(weatherDS);  //for testing the dataset only...

            ForecastClass forecast = new ForecastClass(Plugin.Host, WeatherPlugin.WeatherSettings.ExtendedForecastDays, weatherDS);
            Thread thread = new Thread(new ThreadStart(forecast.SendWeatherNotifications));
            thread.Priority = ThreadPriority.Normal;
            thread.Start();
        }

        public override bool IsValidDirect(Item directItem)
        {   
            return directItem.Properties.ContainsKey("Weather") && (bool)(directItem.Properties["Weather"]) == true;
        }
        #endregion
    }

    class ForecastClass
    {
        private DataSet weatherDS;
        private int numDays;
        private Host host;

        public ForecastClass(Host host, int days, DataSet dataSet)
        {
            this.host = host;
            numDays = days;
            weatherDS = dataSet;
        }

        public void SendWeatherNotifications()
        {
            //TODO: setting for how many days to show...for now default to 3
            
            int partOffset = 0;
            int dayOffset = 0;

            try
            {
                NotificationPackage package = new NotificationPackage();
                package.CaptionClick += package_Click;
                package.MessageClick += package_Click;
                if (weatherDS != null && !weatherDS.Tables.Contains("err"))
                {
                    for (int i = 0; i < numDays; i++)
                    {
                       
                       dayOffset = i;
                       
                       if (i == 0)
                          partOffset = 1;
                       else
                          partOffset = i * 2;

                        package.Message = weatherDS.Tables["part"].Rows[partOffset]["t"].ToString() +
                            "\nHI: " + weatherDS.Tables["day"].Rows[dayOffset]["hi"].ToString() +
                            "\nLOW: " + weatherDS.Tables["day"].Rows[dayOffset]["low"].ToString();

                        package.Caption = weatherDS.Tables["day"].Rows[dayOffset]["t"].ToString() + ", " + weatherDS.Tables["day"].Rows[dayOffset]["dt"].ToString();
                        package.Image = new System.Drawing.Bitmap((Bitmap)Rapier.Kodachi.Weather.Properties.Resources.ResourceManager.GetObject("_" + weatherDS.Tables["part"].Rows[partOffset]["icon"].ToString()), new Size(48, 48));

                        host.Notify(package);
                        Thread.Sleep(3000);
                    }

                }
                else
                {
                    package.Message = "Current Weather Not Available";
                    package.Caption = "Current Weather Not Available";
                    host.Notify(package);
                }
            }
            catch
            {
                NotificationPackage package = new NotificationPackage();
                package.Message = "An unknown error ocurred in the extended forecast!!!";
                package.Caption = "Unknown Error";
                host.Notify(package);
            }
        }

        private void package_Click(NotificationPackage sender)
        {
            string url = String.Format("http://weather.com/weather/local/{0}", HttpUtility.UrlEncode(WeatherPlugin.WeatherSettings.DefaultLocationID));
            Process.Start(url);
        }
    }
}
